import axios from 'axios'
import { Notification, Message } from 'element-ui'
import { getToken, removeToken } from './auth'
import errorCode from './errorCode'
import generateID from './generateID'
import md5 from 'js-md5'
import CryptoJS from 'crypto-js'
import cookie from 'js-cookie'

const whiteList = ['/register/getRegisterSMSWeb', '/register/registerCustomerWeb']

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// Creating axios instance
const service = axios.create({
  //baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'http://18.143.26.199:8081',
  // baseURL: '/mining',
  baseURL: 'http://52.77.134.232:8081', // dev
  //baseURL: 'https://api.chatai.style/', // prod
  withCredentials: true,
  // timeout
  timeout: 30000
})

service.interceptors.request.use(
  (config) => {
	// show loading
	uni.showLoading({
		title: 'loading'
	});
    if (config.url == 'ipServer') {
      // var url = window.location.href
      // var dz_url = url.split('#')[0]
      // config.url = dz_url + config.url
      config.url = 'https://app.chatai.style/ipserver/ip/getCountry'
    } else if (whiteList.indexOf(config.url) < 0) {
      // formatting data
      let data = JSON.stringify(config.data)
      let body = {}
      let bodykey = {}
      const reg = RegExp(/\/api\//)
      // Include /api/
      if (config.url.match(reg)) {
        bodykey = {
          body: data,
          key: md5(data)
        }
      } else {
        body = {
          data: data,
          reqNo: generateID()
        }
        bodykey = {
          body: JSON.stringify(body),
          key: md5(data)
        }
      }
	  console.log(bodykey)

      // DES encryption
      const key = 'duskei_dueu7/32_2333239_4838363ess293w74jsuw'
      var keyHex = CryptoJS.enc.Utf8.parse(key)
      var encrypted = CryptoJS.DES.encrypt(JSON.stringify(bodykey), keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
      // Transfer to base64
      const Base64 = require('js-base64').Base64
      const exStr = Base64.encode(encrypted.toString())

      // Transferring parameters in FormData mode
      let params = new FormData()
      params.append('paramsString', exStr)
      config.data = params
    }

    config.headers['language'] = cookie.get("lang")=='ZH'?2:1
    //
    // if (!getToken()) {
    //   return config
    // } else {
    //   config.headers['token'] = getToken()
    //   return config
    // }
    return config
  },
  (error) => {
    // Do something with request error
    Promise.reject(error)
  }
)

// Response Interceptor
service.interceptors.response.use(
  (res) => {
	uni.hideLoading()
    // Default success status if no status code is set
    const code = res.data.code || '200'
    // Get error information
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code != '200' && code != '751' && code != '752' && code != '601' && code != '715') {
      if (code == '608' && msg) {
        Notification.error({
          title: msg,
          onClose: () => {
            removeToken()
            // window.location.href = '/pages/login'
            // router.push('/login')
			uni.reLaunch({
				url: '/pages/login'
			})
          }
        })
      }
      // Notification.error({
      //   title: msg
      // })
	  // uni.showToast({
	  //     title: msg,
		 //  icon: 'none',
	  //     duration: 3000
	  // }) 
	  if(msg) {
		  Message({
			message: msg,
			type: 'error',
			duration: 5 * 1000
		  })
	  }
      return Promise.reject('error')
    } else {
      // Notification.success(res.data.msg)
      return res.data
    }
  },
  (error) => {
	uni.hideLoading()
    let { msg } = error
    if (msg == 'Network Error') {
      msg = 'Service exception'
    }
	if(msg) {
		Message({
		  message: msg,
		  type: 'error',
		  duration: 5 * 1000
		})
	}
    return Promise.reject(error)
  }
)

export default service